package com.isky.visual.db.resolver;

import com.isky.visual.db.enums.DataStoreDimensionEnums;
import com.isky.visual.db.resolver.annotation.HandlerDataStoreResolver;
import com.isky.visual.db.vo.*;
import org.apache.ibatis.logging.Log;
import org.apache.ibatis.logging.LogFactory;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * TODO 地图数据集解析器
 *
 * @author wenjs
 */
@Component
@HandlerDataStoreResolver(2)
public class MapDataSourceDimensionResolver extends BaseDataSourceDimensionResolver {
    protected Log log = LogFactory.getLog(this.getClass());

    @Override
    public ReportModel buildDataStoreDimension(List<Map<String, Object>> selectMaps, Map<String, String> dimensionsMap) {
        String key1 = dimensionsMap.get(DataStoreDimensionEnums.KEY1.getColumnType());
        String key2 = dimensionsMap.get(DataStoreDimensionEnums.KEY2.getColumnType());
        String key3 = dimensionsMap.get(DataStoreDimensionEnums.KEY3.getColumnType());
        String key4 = dimensionsMap.get(DataStoreDimensionEnums.KEY4.getColumnType());
        String key5 = dimensionsMap.get(DataStoreDimensionEnums.KEY5.getColumnType());

        List<BaseValues> listValue = new ArrayList<>();
        List<String> listName = new ArrayList<>();
        ReportModel rm = new ReportModel();
        try {
            Map<Object, List<Map<String, Object>>> companyNameSet = selectMaps.stream().collect(Collectors.groupingBy(k -> k.get(key1)));

            Set<Object> objects = companyNameSet.keySet();
            for (Object keyname : objects) {
                List<Map<String, Object>> maps = companyNameSet.get(keyname);
                MapValues vs = new MapValues();
                for (Map<String, Object> map : maps) {
                    Long[] mapData = new Long[3];
                    try {
                        String name = String.valueOf(map.get(key2));
                        if (!listName.contains(name)) {
                            listName.add(name);
                        }

                        mapData[0]=new Long(getIntegerDefault(key3, map, 0));
                        mapData[1]=new Long(getInteger(key4, map));
                        mapData[2]=new Long(getInteger(key5, map));
                    } catch (Exception e) {
                        log.error("数据集结果解析：{}", e);
                    }
                    vs.setValue(mapData);
                }
                vs.setName(String.valueOf(keyname));
                listValue.add(vs);
            }

            rm.setNames(listName);
            rm.setValues(listValue);
        } catch (Exception e) {
            log.error(e.getMessage());
        }
        return rm;
    }
}
